package com.corner.presenter.imp;

import com.corner.model.cornerservice.domain.User;
import com.corner.model.cornerservice.helper.UserHelper;
import com.corner.model.leancloud.helper.SmsHelper;
import com.corner.presenter.IGetSmsCodePresenter;
import com.corner.presenter.base.BasePresenter;
import com.corner.ui.view.IGetSmsCodeView;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;

/**
 * Created by Administrator on 2015/7/11，14.47.
 * 描述：
 */
public class GetSmsCodePresenter extends BasePresenter<IGetSmsCodeView> implements IGetSmsCodePresenter {
    boolean hasVertify;

    @Override
    public void getSmsCode(String phoneNum) {
        view.showLoading(true);
        SmsHelper.getSmsCode(phoneNum, null).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1() {
            @Override
            public void call(Object o) {
                hasVertify = false;
                if (view != null) {
                    view.getSmsSucess();
                    view.showLoading(false);
                }
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                if (view != null) {
                    view.getSmsCodeError(throwable.getMessage());
                    view.showLoading(false);
                }
            }
        });
    }

    @Override
    public void vertify(final String phoneNum, String smsCode) {
        view.showLoading(true);
        Action1<User> onNext = new Action1<User>() {
            @Override
            public void call(User user) {
                if (view != null) {
                    view.showLoading(false);
                    if (user!=null){
                        view.loginSucess();
                    }else {
                        view.phoneNumHasNotRegistered();
                    }
                }
            }
        };
        Action1<Throwable> onError = new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                if (view != null) {
                    view.showLoading(false);
                    view.vertifyError(throwable.getMessage());
                }
            }
        };
        if (hasVertify) {
            UserHelper.getPhoneIsHasRegistered(phoneNum).observeOn(AndroidSchedulers.mainThread()).subscribe(onNext, onError);
        } else {
            SmsHelper.verifySMSCode(smsCode, phoneNum).flatMap(new Func1<Object, Observable<User>>() {
                @Override
                public Observable<User> call(Object o) {
                    hasVertify = true;
                    return UserHelper.getPhoneIsHasRegistered(phoneNum);
                }
            }).observeOn(AndroidSchedulers.mainThread()).subscribe(onNext, onError);
        }
    }
}
